package com.teamsun.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.teamsun.cache.CacheManager;
import com.teamsun.entity.TreeItem;
import com.teamsun.rptcfg.BaseRpt;
import com.teamsun.rptcfg.BaseRptColumn;
import com.teamsun.rptcfg.TreeDim;
import com.teamsun.service.IShowRptService;
import org.apache.commons.lang3.StringUtils;
import org.apache.poi.ss.formula.eval.StringValueEval;
import org.apache.poi.util.StringUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.servlet.http.HttpServletRequest;
import java.net.URLDecoder;
import java.util.*;

/**
 * <p>报表中树形数据查询Controller</p>
 */
@Controller
@RequestMapping("/rptTools/treeData")
public class RptTreeController {

    @Autowired
    private IShowRptService showRptService;

	@Autowired
	private CacheManager cacheManager;
	
	@RequestMapping("/tree/{attrName}/{rptId}/{rightValue}/{parentValue}/{needSearch}")
	public String initOrgTree(@PathVariable("attrName") String attrName, @PathVariable("rptId") String rptId,
                              @PathVariable("rightValue") String rightValue, @PathVariable("parentValue") String parentValue,
							  @PathVariable("needSearch") String needSearch, HttpServletRequest request) throws Exception {
		request.setAttribute("compSid", rptId);
		request.setAttribute("attrNameId", (attrName + "Id"));
		request.setAttribute("isMulti", true);
		request.setAttribute("hidAttrId", ("hid_" + attrName));
        request.setAttribute("attrName", attrName);
        request.setAttribute("rightValue", rightValue);
		request.setAttribute("parentValue", parentValue);
		request.setAttribute("needSearch", needSearch);
		request.setAttribute("readOnly", request.getParameter("readOnly"));
        String selfDefineValue = request.getParameter("selfDefineValue");
		String multiTreeMode = request.getParameter("multiTreeMode");
		request.setAttribute("selfDefineValue", selfDefineValue);
		request.setAttribute("multiTreeMode", multiTreeMode);  // 0-只能选择单个tab的树控件  1-可选择多个tab的树控件
		String selfDefineName = request.getParameter("selfDefineName");
		if(StringUtils.isNotBlank(selfDefineName)) {
			//selfDefineName = new String(selfDefineName.getBytes("ISO-8859-1"), "UTF-8");
			selfDefineName = URLDecoder.decode(selfDefineName, "utf-8");
			request.setAttribute("selfDefineName", selfDefineName);
		}

		// 获取缓存的报表配置信息
		BaseRpt rptInfo =  (BaseRpt) cacheManager.getRptCache(rptId);
		// 查询是否配置多个树信息
		boolean multiTree = false;
		List<TreeDim> treeDims = new ArrayList<TreeDim>();
		List<BaseRptColumn> rptColumns = rptInfo.getConditionColumns();
		if(rptColumns != null && rptColumns.size() > 0) {
			for(BaseRptColumn rptColumn : rptColumns) {
				String aliasField = rptColumn.getAliasField();
				if(attrName.equals(aliasField)) {
					treeDims = rptColumn.getTreeDims();
					if(treeDims.size() > 1) {
						multiTree = true;
						break;
					}
				}
			}
		}
		if(multiTree) {
			// 同时配置多个树
			List<String> tabs = new ArrayList<String>();
			List<Map<String, String>> treeParams = new ArrayList<Map<String, String>>();  // 树控件权限控制参数
            Map<String,String> tabTreeIdMap = new HashMap<String, String>();  // 每个tab页的树ID
            Map<String,String> tabTreeNameMap = new HashMap<String, String>();  // 每个tab页的树名称

            // 每个tab是否是第一次点击 (0-否 1-是),当multiTreeMode=0时，需记录tab是否为第一次点击
            // 如果是第一次点击则加载默认值，否则将数值清空
            Map<String, String> tabFirstClick = new HashMap<String, String>();
			for(int i=0; i<treeDims.size(); i++) {
			    TreeDim treeDim = treeDims.get(i);
                List<String> treeIdList = new ArrayList<String>();  // 保存每个tab默认勾选的ID
                List<String> treeNameList = new ArrayList<String>();  // 保存每个tab默认勾选的Name

				String tabName = treeDim.getTabName();  // 每个树tab的名称
				tabs.add(tabName);

				String rightParam = treeDim.getRightParam();  // 树权限控制
				String parentRightParam = treeDim.getParentRightParam();  // 树父权限
                String search = treeDim.getNeedSearch();  // 是否需要搜索框
				Map<String, String> map = new HashMap<String, String>();
				map.put("rightParam", rightParam);
				map.put("parentRightParam", parentRightParam);
                map.put("search", search);
				treeParams.add(map);

                // 获取每个TAB对应的树ID和树Name
                if(StringUtils.isNotBlank(selfDefineValue)) {
                    List<Map<String, Object>> treeDatas = showRptService.queryTreeData(treeDim, rptInfo, selfDefineValue);
                    if(treeDatas != null && treeDatas.size() > 0) {
                        for(Map<String, Object> treeMap : treeDatas) {
                            String code = (String) treeMap.get("code");
                            String name = (String) treeMap.get("name");
                            treeIdList.add(code);
                            treeNameList.add(name);
                        }
                    }
                }
                tabTreeIdMap.put(String.valueOf(i + 1), StringUtils.join(treeIdList, ","));
                tabTreeNameMap.put(String.valueOf(i + 1), StringUtils.join(treeNameList, ","));
			    tabFirstClick.put(String.valueOf(i + 1), "1");
			}
			request.setAttribute("tabs", tabs);
			request.setAttribute("tabCnt", tabs.size());
			request.setAttribute("treeParams", JSONArray.toJSON(treeParams));
            request.setAttribute("tabTreeIdMap", JSON.toJSON(tabTreeIdMap));
            request.setAttribute("tabTreeNameMap", JSON.toJSON(tabTreeNameMap));
            request.setAttribute("tabFirstClick", JSON.toJSON(tabFirstClick));
			return "common/tabTreeIndex";
		} else {
			return "common/treeIndex";
		}
	}
	
	@ResponseBody
	@RequestMapping("/treenode/{rptId}/{attrName}/{rightValue}/{parentValue}")
	public JSONArray selectOrgTree(@PathVariable("rptId") String rptId, @PathVariable("attrName") String attrName,
                                   @PathVariable("rightValue") String rightValue, @PathVariable("parentValue") String parentValue,
								   HttpServletRequest request) {
		String parentId = request.getParameter("id");

        // 获取缓存的报表配置信息
        BaseRpt rptInfo =  (BaseRpt) cacheManager.getRptCache(rptId);

        // 获取维表数据的配置信息
        TreeDim treeDim = new TreeDim();
        List<BaseRptColumn> conditionColumns = rptInfo.getConditionColumns();
        if(conditionColumns != null && conditionColumns.size() > 0) {
            for(BaseRptColumn rptColumn : conditionColumns) {
                String aliasField = rptColumn.getAliasField();
                if(aliasField.equals(attrName)) {
                    treeDim = rptColumn.getTreeDim();
                    break;
                }
            }
        }

        // 查询数据
		if("undefined".equalsIgnoreCase(rightValue)) {
			rightValue = "";
		}
		if("undefined".equalsIgnoreCase(parentValue)) {
			parentValue = "";
		}
        List<Map<String, Object>> treeDatas = showRptService.queryTreeData(treeDim, rightValue, parentValue, parentId, rptInfo);
		return processTreeResult(treeDatas);
	}

	@ResponseBody
	@RequestMapping("/searchTree/{rptId}/{attrName}/{rightValue}/{parentValue}/{searchName}")
	public JSONArray searchTree(@PathVariable("rptId") String rptId, @PathVariable("attrName") String attrName,
								   @PathVariable("rightValue") String rightValue, @PathVariable("parentValue") String parentValue,
								@PathVariable("searchName") String searchName,HttpServletRequest request) throws Exception{
		String parentId = request.getParameter("id");
		if(StringUtils.isNotBlank(searchName)) {
			searchName = URLDecoder.decode(searchName, "utf-8");
		}

		// 获取缓存的报表配置信息
		BaseRpt rptInfo =  (BaseRpt) cacheManager.getRptCache(rptId);

		// 获取维表数据的配置信息
		TreeDim treeDim = new TreeDim();
		List<BaseRptColumn> conditionColumns = rptInfo.getConditionColumns();
		if(conditionColumns != null && conditionColumns.size() > 0) {
			for(BaseRptColumn rptColumn : conditionColumns) {
				String aliasField = rptColumn.getAliasField();
				if(aliasField.equals(attrName)) {
					treeDim = rptColumn.getTreeDim();
					break;
				}
			}
		}

		// 查询数据
		if("undefined".equalsIgnoreCase(rightValue)) {
			rightValue = "";
		}
		if("undefined".equalsIgnoreCase(parentValue)) {
			parentValue = "";
		}

		List<Map<String, Object>> treeDatas = showRptService.queryTreeData(treeDim, rightValue, parentValue, parentId, rptInfo, searchName);
		return processTreeResult(treeDatas);
	}

    @ResponseBody
    @RequestMapping("/tabSearchTree/{rptId}/{attrName}/{rightValue}/{parentValue}/{treeTab}/{searchName}")
    public JSONArray tabSearchTree(@PathVariable("rptId") String rptId, @PathVariable("attrName") String attrName,
                                @PathVariable("rightValue") String rightValue, @PathVariable("parentValue") String parentValue,
                                @PathVariable("treeTab") String treeTab,@PathVariable("searchName") String searchName,HttpServletRequest request) throws Exception{
        String parentId = request.getParameter("id");
        if(StringUtils.isNotBlank(searchName)) {
            searchName = URLDecoder.decode(searchName, "utf-8");
        }

        // 获取缓存的报表配置信息
        BaseRpt rptInfo =  (BaseRpt) cacheManager.getRptCache(rptId);

        // 获取维表数据的配置信息
        TreeDim treeDim = new TreeDim();
        int treeIndex = Integer.valueOf(treeTab);
        List<BaseRptColumn> conditionColumns = rptInfo.getConditionColumns();
        if(conditionColumns != null && conditionColumns.size() > 0) {
            for(BaseRptColumn rptColumn : conditionColumns) {
                String aliasField = rptColumn.getAliasField();
                if(aliasField.equals(attrName)) {
                    treeDim = rptColumn.getTreeDims().get(treeIndex);
                    break;
                }
            }
        }

        // 查询数据
        if("undefined".equalsIgnoreCase(rightValue)) {
            rightValue = "";
        }
        if("undefined".equalsIgnoreCase(parentValue)) {
            parentValue = "";
        }

        List<Map<String, Object>> treeDatas = showRptService.queryTreeData(treeDim, rightValue, parentValue, parentId, rptInfo, searchName);
        return processTreeResult(treeDatas);
    }

    @ResponseBody
    @RequestMapping("/tabTreenode/{rptId}/{attrName}/{rightValue}/{parentValue}/{treeTab}")
    public JSONArray tabTreenode(@PathVariable("rptId") String rptId, @PathVariable("attrName") String attrName,
                                   @PathVariable("rightValue") String rightValue, @PathVariable("parentValue") String parentValue,
                                 @PathVariable("treeTab") String treeTab,HttpServletRequest request) {
        String parentId = request.getParameter("id");

        // 获取缓存的报表配置信息
        BaseRpt rptInfo =  (BaseRpt) cacheManager.getRptCache(rptId);

        // 获取维表数据的配置信息
        TreeDim treeDim = new TreeDim();
        int treeIndex = Integer.valueOf(treeTab);
        List<BaseRptColumn> conditionColumns = rptInfo.getConditionColumns();
        if(conditionColumns != null && conditionColumns.size() > 0) {
            for(BaseRptColumn rptColumn : conditionColumns) {
                String aliasField = rptColumn.getAliasField();
                if(aliasField.equals(attrName)) {
                    treeDim = rptColumn.getTreeDims().get(treeIndex);
                    break;
                }
            }
        }

        // 查询数据
        if("undefined".equalsIgnoreCase(rightValue)) {
            rightValue = "";
        }
        if("undefined".equalsIgnoreCase(parentValue)) {
            parentValue = "";
        }
        List<Map<String, Object>> treeDatas = showRptService.queryTreeData(treeDim, rightValue, parentValue, parentId, rptInfo);
        return processTreeResult(treeDatas);
    }

    /**
     * 格式化树形数据
     * @param treeDatas
     * @return
     */
	private JSONArray processTreeResult(List<Map<String, Object>> treeDatas) {
		if(treeDatas == null || treeDatas.isEmpty()){
			return null;
		}
		JSONArray jsonArr = new JSONArray();

		Set<String> codeSet = new HashSet<String>();
		for(Map<String, Object> treeData : treeDatas) {
			String code = (String) treeData.get("code");
			codeSet.add(code);
		}
		for(Map<String, Object> treeData : treeDatas) {
			String upcode = (String) treeData.get("upcode");
			if(!codeSet.contains(upcode)) {
				TreeItem item = new TreeItem();
				item.setId((String) treeData.get("code"));
				item.setName((String) treeData.get("name"));
				item.setPId(upcode);
				item.setOpen(false);
				item.setIsParent("true");
				jsonArr.add(item);
			}
		}
		return jsonArr;
	}
}
